package com.alex.service;

import com.alex.dao.OfflineMessage;
import com.alibaba.fastjson.JSONObject;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@ServerEndpoint("/imserver/{userId}")
public class WebSocketServer {

    private static ApplicationContext applicationContext;

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static AtomicInteger onlineNum = new AtomicInteger();

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<String, Session>();

    public static void setApplicationContext(ApplicationContext applicationContext) {
        WebSocketServer.applicationContext = applicationContext;
    }

    //发送消息
    public void sendMessage(Session session, String message) throws IOException {
        if (session != null) {
            synchronized (session) {
                System.out.println("发送数据：" + message);
                session.getBasicRemote().sendText(message);
            }
        }
    }

    //给指定用户发送信息
    public void sendInfo(String userName, String message) {
        Session session = sessionPools.get(userName);
        OfflineMessageService offlineMessageService = (OfflineMessageService) applicationContext.getBean("offlineMessageService");
        try {
            if (session == null) {
                // 持久化信息
                offlineMessageService.insert(userName, message);
            } else {
                sendMessage(session, message);
            }
        } catch (Exception e) {
            e.printStackTrace();
            offlineMessageService.insert(userName, message);
        }
    }

    //建立连接成功调用
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userName) {
        sessionPools.put(userName, session);
        addOnlineCount();
        System.out.println(userName + "加入webSocket！当前人数为" + onlineNum);
        try {
            sendMessage(session, "欢迎" + userName + "加入连接！");
            OfflineMessageService offlineMessageService = (OfflineMessageService) applicationContext.getBean("offlineMessageService");
            List<OfflineMessage> offlineMessages = offlineMessageService.listByUserIdOrderByDate(userName);
            if (offlineMessages != null) {
                for (OfflineMessage message : offlineMessages) {
                    sendInfo(message.getUserId(), message.getMessage());

                    offlineMessageService.updateMessageStatus(message.getId());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //关闭连接时调用
    @OnClose
    public void onClose(@PathParam(value = "userId") String userName) {
        sessionPools.remove(userName);
        subOnlineCount();
        System.out.println(userName + "断开webSocket连接！当前人数为" + onlineNum);
    }

    /**
     * 单发还是群发:
     * 1. 在于是发给所有在线的Session; 还是某个session
     * 2. 在创建连接的时候, 需要关联用户和Session
     */
    //收到客户端信息
    @OnMessage
    public void onMessage(String message) throws IOException {
        JSONObject jsonObject = JSONObject.parseObject(message);
        message = "客户端：" + message + ",已收到";
        System.out.println(message);


        // 单发
        sendInfo(jsonObject.getString("toUserId"), jsonObject.getString("contentText"));

        // 群发
        /*for (Session session: sessionPools.values()) {
            try {
                sendMessage(session, message);
            } catch(Exception e){
                e.printStackTrace();
                continue;
            }
        }*/
    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("发生错误");
        throwable.printStackTrace();
    }

    public static void addOnlineCount() {
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }
}